// index.js
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

// 引入API模块
const { api } = require('../../utils/api');

// 工具函数：格式化时间
function formatDateTime(dateStr) {
  if (!dateStr) return '';
  return dateStr.replace('T', ' ').slice(0, 16);
}

Page({
  data: {
    motto: 'Hello World',
    userInfo: {
      avatarUrl: defaultAvatarUrl,
      nickName: '',
    },
    hasUserInfo: false,
    canIUseGetUserProfile: wx.canIUse('getUserProfile'),
    canIUseNicknameComp: wx.canIUse('input.type.nickname'),
    // 轮播图数据
    banners: [],
    // 打卡状态
    punchInStatus: false,
    // 社刊数据
    magazines: [],
    showMagazineModal: false,
    // 精品课程
    featuredCourses: [],
    // 专家讲师
    teachers: [],
  },
  bindViewTap() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onChooseAvatar(e) {
    const { avatarUrl } = e.detail
    const { nickName } = this.data.userInfo
    this.setData({
      "userInfo.avatarUrl": avatarUrl,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
    })
  },
  onInputChange(e) {
    const nickName = e.detail.value
    const { avatarUrl } = this.data.userInfo
    this.setData({
      "userInfo.nickName": nickName,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
    })
  },
  getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    })
  },
  // 页面加载
  onLoad() {
    this.loadData();
  },
  
  // 下拉刷新
  onPullDownRefresh() {
    this.loadData().then(() => {
      wx.stopPullDownRefresh();
    });
  },
  
  // 加载所有数据
  async loadData() {
    wx.showLoading({
      title: '加载中',
    });
    
    try {

      // 获取轮播图数据
      const banners = await api.getBanners()
      this.setData({
        banners: banners.data || [],
      })
      
      // 获取周刊数据
      const magazinesRes = await api.getMagazines()
      const magazines = (magazinesRes.data || []).map(item => ({
        ...item,
        createTime: formatDateTime(item.createTime)
      }));
      this.setData({
        magazines
      })

      // 课程数据
      const coursesRes = await api.getFeaturedCourses()
      const courses = (coursesRes.data || []).map(item => ({
        ...item,
        createTime: formatDateTime(item.createTime)
      }));
      this.setData({
        featuredCourses: courses || []
      })

      // 老师数据
      const teachersRes = await api.getTeachers()
      const teachers = (teachersRes.data || []).map(item => ({
        ...item,
        createTime: formatDateTime(item.createTime)
      }));
      this.setData({
        teachers: teachers || []
      })

    } catch (error) {
      wx.showToast({
        title: '加载失败，请重试',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  },
  
  // 打卡功能
  async onPunchIn() {
    if (this.data.punchInStatus) {
      wx.showToast({
        title: '今日已打卡',
        icon: 'none'
      });
      return;
    }
    
    wx.showLoading({
      title: '打卡中',
    });
    
    try {
      const result = await api.punchIn();
      if (result.code == 200) {
        this.setData({
          punchInStatus: true
        });
        wx.showToast({
          title: '打卡成功'
        });
      } else {
        wx.showToast({
          title: result.message || '打卡失败',
          icon: 'none'
        });
      }
    } catch (error) {
      wx.showToast({
        title: '打卡失败，请重试',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  },
  
  // 打开社刊弹窗
  onOpenMagazine() {
    this.setData({
      showMagazineModal: true
    });
  },

  // 关闭社刊弹窗
  onCloseMagazineModal() {
    this.setData({
      showMagazineModal: false
    });
  },
  
  // 选择社刊并打开PDF预览
  onMagazineSelect(e) {
    const magazine = e.currentTarget.dataset.item;
    this.setData({ showMagazineModal: false });
    wx.navigateTo({
      url: `/pages/magazine/detail?data=${encodeURIComponent(JSON.stringify(magazine))}`
    });
  },
  
  // 轮播图点击
  onBannerTap(e) {
    const bannerId = e.currentTarget.dataset.id;
    const banner = this.data.banners.find(item => item.id === bannerId);
    
    if (banner && banner.linkUrl) {
      wx.navigateTo({
        url: banner.linkUrl
      });
    }
  },
  
  // 更多课程
  onMoreCourses() {
    wx.switchTab({
      url: '/pages/school/index'
    });
  },
  
  // 更多讲师
  onMoreTeachers() {
    wx.navigateTo({
      url: '/pages/teacher/list'
    });
  },
  
  // 课程详情
  onCourseDetail(e) {
    const courseId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/school/detail?id=${courseId}`
    });
  },
  
  // 课程跳转到外部链接
  onCourseJump(e) {
    const jumpUrl = e.currentTarget.dataset.url;
    const courseId = e.currentTarget.dataset.id;
    
    if (jumpUrl) {
      // 如果有跳转链接，打开网页
      wx.navigateTo({
        url: `/pages/webview/index?url=${encodeURIComponent(jumpUrl)}`
      });
    } else {
      // 如果没有跳转链接，打开详情页
      this.onCourseDetail(e);
    }
  },
  
  // 讲师详情
  onTeacherDetail(e) {
    const teacherId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/teacher/detail?id=${teacherId}`
    });
  }
})
